package com.cyl.XmlDemo.listener;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import com.cyl.XmlDemo.entity.RoomInfo;
import com.cyl.XmlDemo.entity.RoomList;
import com.cyl.XmlDemo.entity.ShiroPrincipal;
import com.cyl.XmlDemo.entity.UserInfo;
import com.cyl.XmlDemo.entity.UserList;
import com.cyl.XmlDemo.utils.ShiroUtils;

@Component
public class SessionDisconnectListener implements ApplicationListener<SessionDisconnectEvent> {
	
	private static final Logger logger = LoggerFactory.getLogger(SessionDisconnectListener.class);
	
	@Autowired
	private RoomList roomList;
	
	@Autowired
	private UserList userList;

	@Override
	public void onApplicationEvent(SessionDisconnectEvent event) {
		StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
//		String uid = headerAccessor.getSessionAttributes().get("sessionId").toString();
		//游客直接使用sessionid当作用户名
		String uid = null;
		ShiroPrincipal shiroPrincipal = ShiroUtils.getPrincipal();
		if(shiroPrincipal != null){
			uid = shiroPrincipal.getUser().getUsername();
		}else{
			uid = headerAccessor.getSessionAttributes().get("sessionId").toString();
		}
		//移除现存用户列表的当前用户
		UserInfo userInfo = userList.getUser(uid);
		userList.delUser(uid);
		//移除房间中的当前用户
		RoomInfo roomInfo = roomList.getRoom(userInfo.getCurrentRoom());
		roomInfo.removeUser(uid);
		//TODO 发送用户离开信息
		//TODO 登录用户注销
	}

}
